<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">

      <el-form-item label="类型" prop="supplyTypeId">
        <el-cascader v-model="formData.supplyTypeId" :options="supplyList"
          :props="{ value: 'id', label: 'typeName', children: 'children', checkStrictly: true }" class="w-1/1"
          popper-class='cascader' clearable filterable placeholder="请选择信息类型" @change="supplyTypeChange" />
      </el-form-item>
      <el-form-item label="香型" prop="fragranceType">
        <el-select v-model="formData.fragranceType">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ODOR_TYPE)  " :key="dict.label" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="统计年份" prop="showYear">
        <el-select v-model="formData.showYear">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YEAR)  " :key="dict.label" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="统计名称" prop="countName">
        <el-input v-model="formData.countName" placeholder="请输入统计名称" />
      </el-form-item>
      <el-form-item label="统计包装" prop="packing">
        <el-select v-model="formData.packing">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PACKING) " :key="dict.label" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="容错名称" prop="failoverName">
        <el-input type="textarea" v-model="formData.failoverName" placeholder="容错名称用英文逗号隔开" :rows="8" />
      </el-form-item>

      <el-form-item label="是否可见" prop="visible">
        <el-select v-model="formData.visible" placeholder="请选择是否可见" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.IS_NO)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序号" prop="sort">
        <el-input-number v-model="formData.sort" :min="-1" placeholder="请输入排序号" />
        <span style="font-size:12px;margin-left:10px;color: #FAAD14;">*：值越小排序越靠前，最小值-1</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { CountNameConfigApi, CountNameConfigVO } from '@/api/wine/countnameconfig'
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { handleTree } from '@/utils/tree'
import { SupplyInfoApi } from '@/api/wine/supplyinfo'

/** 统计名称配置 表单 */
defineOptions({ name: 'CountNameConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  groupNumber: 1,
  supplyTypeId: 0,
  showYear: 1,
  fragranceType:1,
  countName: undefined,
  packing: 1,
  failoverName: undefined,
  visible: 1,
  sort: 1
})

const formRules = reactive({
  countName: [{ required: true, message: '统计名称不能为空', trigger: 'blur' }],
  failoverName: [{ required: true, message: '容错名称不能为空', trigger: 'blur' }],
  visible: [{ required: true, message: '是否可见不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
let supplyList = ref() // 分类树

onMounted(async () => {
  // 获得分类树
  const supply = await SupplyInfoApi.typeList({})
  supplyList.value = handleTree(supply)
})
const supplyTypeChange = (node) => {
  if (node) {
    formData.value.supplyTypeId = node[node?.length - 1]
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CountNameConfigApi.getCountNameConfig(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CountNameConfigVO
    if (formType.value === 'create') {
      await CountNameConfigApi.createCountNameConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await CountNameConfigApi.updateCountNameConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    groupNumber: 1,
    supplyTypeId: 0,
    showYear: 1,
    fragranceType:1,
    countName: undefined,
    packing: 1,
    failoverName: undefined,
    visible: 1,
    sort: 1
  }
  formRef.value?.resetFields()
}
</script>
